<template>
  <div class="container">
    <div class="map-data-list">
      <div class="search-wrapper">
        <el-form :model="pathInfo" label-width="80px" ref="ruleForm">
          <el-form-item
            label="始发地:"
            prop="start"
            :rules="{
              required: true,
              message: '始发地不能为空',
              trigger: 'blur',
            }"
          >
            <el-input class="map-input" v-model="pathInfo.start"></el-input>
          </el-form-item>
          <el-form-item
            label="目的地:"
            prop="end"
            :rules="{
              required: true,
              message: '目的地不能为空',
              trigger: 'blur',
            }"
          >
            <el-input class="map-input" v-model="pathInfo.end"></el-input>
          </el-form-item>
          <div class="btn-wrapper">
            <el-button class="center-btn" type="primary" @click="submit"
              >搜索</el-button
            >
          </div>
        </el-form>
      </div>
      <div class="data-list">
        <div
          class="drivecircuits"
          v-if="
            routeList.drivecircuits &&
            Object.keys(routeList.drivecircuits).length
          "
        >
          <div class="title">精确结果</div>
          <div class="line"></div>
          <div
            class="data-wrapper"
            :class="i === curItem ? 'active' : ''"
            v-for="(v, i) in routeList.drivecircuits"
            :key="v.id"
          >
            <div class="path-title" @click="createRoute(v, i, 'curItem')">
              名称：{{ v.startname }} --- {{ v.destinationname }}
            </div>
            <div class="path-title" @click="createRoute(v, i, 'curItem')">
              尺寸：{{ v.carsize }}
            </div>
            <div class="path-title" @click="createRoute(v, i, 'curItem')">
              吨位：{{ v.tonnage }}
            </div>
            <div class="path-title" @click="createRoute(v, i, 'curItem')">
              时间：{{ v.routestarttime }}
              <span v-if="v.routestarttime && v.routeendtime">至</span>
              {{ v.routeendtime }}
            </div>
            <!-- <el-link class="copy-link" type="primary" @click="copyPath"
              >复制路径</el-link
            > -->
            <div class="location-desc" @click="createRoute(v, i, 'curItem')">
              备注：{{ v.locationdescriptioninchinese }}
            </div>
          </div>
        </div>
        <div
          class="dimDrivecircuits"
          v-if="
            routeList.dimDrivecircuits &&
            Object.keys(routeList.dimDrivecircuits).length
          "
        >
          <div class="title">模糊结果</div>
          <div class="line"></div>
          <div
            class="data-wrapper"
            :class="i === curItemD ? 'active' : ''"
            v-for="(v, i) in routeList.dimDrivecircuits"
            :key="v.id"
          >
            <div class="path-title" @click="createRoute(v, i, 'curItemD')">
              名称：{{ v.startname }} --- {{ v.destinationname }}
            </div>
            <div class="path-title" @click="createRoute(v, i, 'curItemD')">
              尺寸：{{ v.carsize }}
            </div>
            <div class="path-title" @click="createRoute(v, i, 'curItemD')">
              吨位：{{ v.tonnage }}
            </div>
            <div class="path-title" @click="createRoute(v, i, 'curItemD')">
              时间：{{ v.routestarttime }} 至 {{ v.routeendtime }}
            </div>
            <!-- <el-link class="copy-link" type="primary" @click="copyPath"
              >复制路径</el-link
            > -->
            <div class="location-desc" @click="createRoute(v, i, 'curItemD')">
              备注：{{ v.locationdescriptioninchinese }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      class="map-wrapper"
      v-loading="loading"
      element-loading-text="路线载入中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.6)"
    >
      <div id="map"></div>
    </div>
    <input type="text" class="shadowInput" ref="url" v-model="text" />
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { listDrivecircuit } from "@/api/system/drivecircuit";

export default {
  data() {
    return {
      pathInfo: {
        start: "",
        end: "",
      },
      loading: false,
      map: null,
      driving: null,
      geocoder: null,
      routeList: {},
      num: 0,
      text: "",
      pathNum: 0,
      route: [],
      sort: {},
      pathSort: {},
      curItem: "",
      curItemD: "",
      routers: [],
    };
  },
  watch: {
    pathNum: {
      handler: function (val) {
        if (this.route.length === val) {
          let _this = this;
          let str = "";
          for (let i = 0; i < this.route.length; i++) {
            str += this.pathSort[i] + "-";
          }
          str = str.substring(0, str.length - 1);
          this.$copyText(str).then(
            function (e) {
              _this.$message.success("复制成功");
            },
            function (e) {
              _this.$message.error("复制失败");
            }
          );
        }
      },
    },
  },
  methods: {
    copyPath() {
      let _this = this;
      this.pathNum = 0;
      this.pathSort = {};
      for (let i = 0; i < this.route.length; i++) {
        let item = this.route[i];
        this.geocoder.getAddress(
          new AMap.LngLat(item[0], item[1]),
          function (status, { regeocode }) {
            if (status === "complete" && regeocode) {
              _this.pathSort[i] = regeocode.formattedAddress;
            }
            _this.pathNum++;
          }
        );
      }
    },
    createRoute(data, index, type) {
      if (this.loading) {
        this.$message.warning("路线载入中,请稍后更换线路...");
        return false;
      }
      this[type] = index;
      if (type === "curItem") this.curItemD = "";
      else this.curItem = "";
      this.loading = true;
      this.map.clearMap();
      this.route = JSON.parse(data.pointposition);
      this.search();
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.map.clearMap();
          listDrivecircuit({
            startname: this.pathInfo.start,
            destinationname: this.pathInfo.end,
          }).then(({ errCode, data }) => {
            if (errCode == 0) this.routeList = data;
            else this.$message.error("网络错误");
          });
        } else {
          return false;
        }
      });
    },
    search() {
      let _this = this;
      this.routers = [];
      this.sort = {};
      this.num = 0;
      for (let i = 0; i < this.route.length; i++) {
        let item = this.route[i];
        this.routers.push(new AMap.LngLat(item[0], item[1]));
      }
      let length = this.routers.length;
      let start = this.routers[0];
      let end = this.routers[length - 1];
      let waypoints = [];
      if (this.routers.length > 2) {
        let arr = [...this.routers];
        waypoints = arr.splice(1, arr.length - 2);
      }
      this.driving.search(start, end, { waypoints }, function (status, result) {
        if (status !== "complete") {
          this.$message.error("网络错误");
        }
        _this.loading = false;
      });
    },
    initMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "f5c564b72aea4ec517dd3ea4d86c78f8",
      };
      AMapLoader.load({
        key: "8e6281c734527f3c062fa0ec7d642731",
        version: "1.4.15",
        plugins: [
          "AMap.Scale",
          "AMap.ToolBar",
          "AMap.Driving",
          "AMap.MapType",
          "AMap.Geocoder",
          "AMap.DragRoute",
          "AMap.Geolocation",
          "AMap.PlaceSearch",
          "AMap.AutoComplete",
          "AMap.ElasticMarker",
          "AMap.DistrictSearch",
          "AMap.AdvancedInfoWindow",
        ],
      })
        .then((AMap) => {
          this.map = new AMap.Map("map", {
            resizeEnable: true,
            center: [105, 38],
            zoom: 4.7,
          });
          let toolbar = new AMap.ToolBar();
          this.map.addControl(toolbar);
          this.driving = new AMap.Driving({
            map: this.map,
          });
          this.geocoder = new AMap.Geocoder({
            radius: 10000,
          });
        })
        .catch((e) => {
          this.$message.error("网络错误");
        });
    },
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    this.map.clearMap();
    this.map.destroy();
  },
};
</script>
<style lang='scss' scoped>
.container {
  color: #606266;
  display: grid;
  grid-template-columns: 360px auto;
  height: 100%;

  .map-data-list {
    display: grid;
    grid-template-rows: 200px auto;
    height: 100%;
    border-right: solid 1px #e6ebfb;

    .search-wrapper {
      padding-top: 28px;

      .btn-wrapper {
        width: 100%;

        .center-btn {
          width: 120px;
          margin-left: calc(50% - 60px);
        }
      }

      border-bottom: solid 1px #e6ebfb;
    }

    .data-list {
      cursor: pointer;
      height: calc(100vh - 250px);
      overflow: hidden;
      overflow-y: auto;
      font-size: 14px;

      .line {
        height: 1px;
        background: #e6ebfb;
      }

      .title {
        text-align: center;
        padding: 12px 0;
      }

      .path-title {
        padding: 0 12px;
        padding-top: 12px;
      }

      .copy-link {
        margin: -20px 12px;
        float: right;
        display: none;
      }

      .location-desc {
        padding: 12px;
      }

      .active {
        background: rgba(#1c1f20, 0.1);

        .copy-link {
          display: block;
        }
      }

      .data-wrapper {
        &:hover {
          background: rgba(#1c1f20, 0.1);
        }

        border-bottom: solid 1px #e6ebfb;
      }
    }
  }

  .map-wrapper {
    height: 100%;

    #map {
      width: 100%;
      height: 100%;
      margin: 0 auto;
    }
  }
}

.shadowInput {
  position: absolute;
  top: -10000px;
  left: -10000px;
  width: 1px;
  z-index: -1;
}

::v-deep .el-form-item__label {
  font-weight: 500;
}
</style>